package io.gitee.yxsnake.embark.web.core.utils;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.gitee.yxsnake.embark.web.core.constant.Commons;
import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * @author snake
 * @description
 * @since 2024/10/16 23:56
 */

public class ThreadMdcUtil {
    public static void setTraceIdIfAbsent() {
        if (MDC.get(Commons.TRACE_ID) == null) {
            MDC.put(Commons.TRACE_ID, IdWorker.getTimeId());
        }
    }

    public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
